package com.af.community.smart.utils

import com.af.community.smart.viewmodel.BaseViewModel
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.lzy.okgo.utils.OkLogger
import com.vector.update_app.HttpManager
import org.json.JSONObject

import java.io.File

/**
 * 使用OkGo实现接口
 */
class OkGoUpdateHttpUtil : HttpManager {
    /**
     * 异步get
     *
     * @param url      get请求地址
     * @param params   get参数
     * @param callBack 回调
     */
    override fun asyncGet(
        url: String,
        params: Map<String, String>,
        callBack: HttpManager.Callback
    ) {
        OkGo.get<String>(url)
            .params(getParams(params))
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    callBack.onResponse(response.body())
                }

                override fun onError(response: Response<String>) {
                    super.onError(response)
                    callBack.onError("异常")
                }
            })
    }

    /**
     * 异步post
     *
     * @param url      post请求地址
     * @param params   post请求参数
     * @param callBack 回调
     */
    override fun asyncPost(
        url: String,
        params: Map<String, String>,
        callBack: HttpManager.Callback
    ) {
        OkGo.post<String>(url)
            .params(getParams(params))
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    callBack.onResponse(response.body())
                }

                override fun onError(response: Response<String>) {
                    super.onError(response)
                    callBack.onError("异常")
                }
            })
    }

    /**
     * 下载
     *
     * @param url      下载地址
     * @param path     文件保存路径
     * @param fileName 文件名称
     * @param callback 回调
     */
    override fun download(
        url: String,
        path: String,
        fileName: String,
        callback: HttpManager.FileCallback
    ) {
        OkGo.get<File>(url)
            .execute(object : com.lzy.okgo.callback.FileCallback(path, fileName) {
                override fun onSuccess(response: Response<File>) {
                    callback.onResponse(response.body())
                }

                override fun onStart(request: Request<File, out Request<*, *>>?) {
                    super.onStart(request)
                    callback.onBefore()
                }

                override fun onError(response: Response<File>) {
                    super.onError(response)
                    callback.onError("异常")
                }

                override fun downloadProgress(progress: Progress) {
                    super.downloadProgress(progress)

                    callback.onProgress(progress.fraction, progress.totalSize)
                }
            })
    }

    private fun getParams(params: Map<String, Any>): HttpParams {
        val data = JSONObject().apply { params.forEach { put(it.key, it.value) } }.toString()
        val timestamp = System.currentTimeMillis()
        val builder =
            StringBuilder().append("cs_core")
                .append("timestamp").append(timestamp)
                .append("plat").append("android")
                .append("v").append(BaseViewModel.mVersion)
                .append("data").append(data)
                .append("cs_core")
                .toString()

        OkLogger.i("[params]", data)

        return HttpParams().apply {
            put("data", data)
            put("plat", "android")
            put("sign", MD5.md5(builder))
            put("timestamp", timestamp)
            put("tk", 0)
            put("v", BaseViewModel.mVersion)
        }
    }

}